/**
 * 
 */
package com.james.wee.shuangseqiu.open;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import com.james.wee.shuangseqiu.bo.Cardno;
import com.james.wee.shuangseqiu.bo.Cunt;
import com.james.wee.shuangseqiu.bo.IDBBo;
import com.james.wee.shuangseqiu.bo.OpenNumber;
import com.james.wee.shuangseqiu.bo.QueryType;
import com.james.wee.shuangseqiu.bo.ShaNum;
import com.james.wee.shuangseqiu.dafenqissq.DaFenQiSSQ;
import com.james.wee.shuangseqiu.db.DB;
import com.james.wee.shuangseqiu.killnum.KillNumberDb;
import com.james.wee.shuangseqiu.tools.ToolsUtil;

/**
 * @author JamesWee
 * 
 */
public class OpenData {

	/**
	 * 计算下一期的杀号
	 * 
	 * @throws Exception
	 */
	public void showNextShahao() throws Exception {
		OpenNumber openobj = getMaxId();
		OpenNumber prevObj = null;
		KillNumberDb kdb = new KillNumberDb();
		OpenNumber netxObj = new OpenNumber();
		List<IDBBo> nextOpenlist = DB.getInstance().queryBoList(
				"select * from OpenNumber where id in(" + (openobj.getId() - 1)
						+ ") order by id desc", OpenNumber.class);
		prevObj = (OpenNumber) nextOpenlist.get(0);
		kdb.shahaoToOpenNumber(openobj, netxObj, prevObj);
		System.out.println("-------------"
				+ (Integer.parseInt(openobj.getOpennum()) + 1)
				+ "期杀号-------------");
		netxObj.printShaHao();
		String s = netxObj.getXingsha() + "," + netxObj.getKaijianghezhisplit()
				+ "," + netxObj.getKaijiangjianac() + ","
				+ netxObj.getKaijiangjianlan() + ","
				+ netxObj.getKaijiangliangqijian() + ","
				+ netxObj.getKaijiangweihesplit() + ","
				+ netxObj.getKaijiangxiangjian() + ","
				+ netxObj.getMuiltyhezhisplit();
		Map<String, String> m = new TreeMap<String, String>();
		for (int i = 1; i < 34; i++) {
			if (i < 10)
				m.put("0" + i, "0" + i);
			else
				m.put("" + i, "" + i);
		}
		String[] cs = s.replaceAll(" ", "").split(",");
		for (String a : cs) {
			m.remove(a);
		}
		System.out.println("未杀之号：" + m.keySet());
		DaFenQiSSQ ds = new DaFenQiSSQ(openobj);
		System.out.println("-------------达芬奇密码-------------");
		System.out.println("第一密码:" + ds.calcOpenNumFirstPWD());
		System.out.println("第二密码:" + ds.calcOpenNumTwoPWD());
		System.out.println("第三密码:" + ds.calcOpenNumThreePWD());
		System.out.println("第四密码:" + ds.calcOpenNumFourPWD());
	}

	/**
	 * 显示指定的期号并依此计算下一期的杀号
	 * 
	 * @param openNum
	 */
	public void showPointShahao(String openNum) {
		try {
			List<IDBBo> list = DB.getInstance().queryBoList(
					"SELECT * FROM OpenNumber WHERE opennum='" + openNum + "'",
					OpenNumber.class);
			OpenNumber on = null;
			for (IDBBo bo : list) {
				on = (OpenNumber) bo;
				System.out.println("开奖期号：" + on.getOpennum() + "\t开奖号码："
						+ on.sixRedNum() + "|" + on.getN_blue());
				on.printShaHao();
			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 更新最新开奖数据
	 * 
	 * @param opennumber
	 * @throws Exception
	 */
	public OpenNumber insertLastOpenData(OpenNumber openobj) throws Exception {
		String zumaIDS = queryCardNoByLastOpenData(openobj.sixRedNum());
		String maxnum = getMaxId().getOpennum();
		try {

			if (null == openobj.getOpennum()) {
				String year = ""
						+ java.util.Calendar.getInstance().get(Calendar.YEAR);
				if (maxnum.indexOf(year) != -1) {
					openobj.setOpennum("" + (Integer.parseInt(maxnum) + 1));
				} else {
					openobj.setOpennum("" + year + "001");
				}

			}
			openobj.setZumamaping(zumaIDS);
			openobj = (OpenNumber) DB.getInstance().save(openobj);
			// 计算杀号
			KillNumberDb kdb = new KillNumberDb();
			List<IDBBo> openlist = DB.getInstance().queryBoList(
					"select * from OpenNumber where id in("
							+ (openobj.getId() - 1) + ","
							+ (openobj.getId() - 2) + ") order by id desc",
					OpenNumber.class);
			OpenNumber currentObj = (OpenNumber) openlist.get(0);
			OpenNumber prevObj = (OpenNumber) openlist.get(1);
			kdb.shahaoToOpenNumber(currentObj, openobj, prevObj);
			// 下期杀号
			OpenNumber netxObj = new OpenNumber();
			List<IDBBo> nextOpenlist = DB.getInstance().queryBoList(
					"select * from OpenNumber where id in("
							+ (openobj.getId() - 1) + ") order by id desc",
					OpenNumber.class);
			prevObj = (OpenNumber) nextOpenlist.get(0);
			kdb.shahaoToOpenNumber(openobj, netxObj, prevObj);
			netxObj.printShaHao();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return openobj;
	}

	/**
	 * 根据最新开奖数据查询与组码关系
	 * 
	 * @param opennumber
	 * @return
	 */
	public String queryCardNoByLastOpenData(String opennumber) throws Exception {
		StringBuilder sbuild = new StringBuilder(
				"SELECT ZUMAID FROM CARDNO WHERE ");
		String[] openes = opennumber.split(",");
		String and = "";
		for (String str : openes) {
			sbuild.append(and).append(ToolsUtil.getStr(str)).append("='")
					.append(str).append("'");
			and = " AND ";
		}
		List<IDBBo> list = DB.getInstance().queryBoList(sbuild.toString(),
				Cardno.class);
		String result = "";
		String du = "";
		if (null != list) {
			for (IDBBo bo : list) {
				result += du + ((Cardno) bo).getZumaid();
				du = ",";
			}
		}
		return result;
	}

	/**
	 * 获取数据库最新一期的开奖数据对象
	 * 
	 * @return
	 * @throws Exception
	 */
	public OpenNumber getMaxId() throws Exception {
		Method method = OpenNumber.class.getMethod("countOrMaxRecd",
				QueryType.class);
		String sql = method.invoke(OpenNumber.class.newInstance(),
				QueryType.MAX).toString();
		List<IDBBo> ilist = DB.getInstance().queryBoList(sql, OpenNumber.class);
		return ((OpenNumber) ilist.get(0));
	}

	/**
	 * 计算开奖数据与组码的HTML页面
	 * 
	 * @throws Exception
	 */
	public void countAllOpenData() throws Exception {
		List<IDBBo> openlist = DB.getInstance().queryBoList(
				"select * from OpenNumber order by id desc", OpenNumber.class);
		List<Cunt> cuntlist = new ArrayList<Cunt>();
		Cunt cunt = null;
		OpenNumber on = null;
		if (null != openlist && !openlist.isEmpty()) {
			for (IDBBo bo : openlist) {
				on = (OpenNumber) bo;
				cunt = strToCunt(on.getZumamaping(),
						on.sixRedNum() + "|" + on.getN_blue(), on.getOpennum());
				cuntlist.add(cunt);
			}
		}
		countAllOpenDatatoHtml(cuntlist);
	}

	private Cunt strToCunt(String zuma, String opendata, String seqnno) {
		Class<Cunt> clazz = Cunt.class;
		Method method = null;
		String[] ss = zuma.split(",");

		Cunt obj = null;
		try {
			obj = clazz.newInstance();
			for (String s : ss) {
				method = clazz.getMethod("set" + ToolsUtil.getStr(s),
						String.class);
				method.invoke(obj, s);
				method = clazz.getMethod("setSeqno", String.class);
				method.invoke(obj, seqnno);
				method = clazz.getMethod("setOpenNo", String.class);
				method.invoke(obj, opendata);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return obj;
	}

	public void contShaHaoToHtml() throws Exception {
		OpenNumber openobj = null;
		OpenNumber prevObj = null;
		KillNumberDb kdb = new KillNumberDb();
		OpenNumber netxObj = null;// new OpenNumber();
		// List<IDBBo> nextOpenlist = DB.getInstance().queryBoList(
		// "select * from OpenNumber where id in(" + (openobj.getId() - 1)
		// + ") order by id desc", OpenNumber.class);
		// prevObj = (OpenNumber) nextOpenlist.get(0);
		// kdb.shahaoToOpenNumber(openobj, netxObj, prevObj);
		// netxObj.setOpennum("" + (Integer.parseInt(openobj.getOpennum()) +
		// 1));
		BufferedWriter bw = null;
		BufferedReader br = null;
		InputStream is = OpenData.class.getResourceAsStream("/sha.html");
		File file = new File("ShaCount.html");
		bw = new BufferedWriter(new FileWriter(file));
		br = new BufferedReader(new InputStreamReader(is));
		List<IDBBo> list = DB.getInstance().queryBoList(
				"select * from OpenNumber order by id desc", OpenNumber.class);
		for (int j = 0, len = list.size(); j < len; j++) {
			openobj = (OpenNumber) list.get(j);
			if (j < len - 2)
				prevObj = (OpenNumber) list.get(j + 2);
			if (j == 0) {
				netxObj = new OpenNumber();
				netxObj.setOpennum(""
						+ (Integer.parseInt(openobj.getOpennum()) + 1));
				kdb.shahaoToOpenNumber(openobj, netxObj, prevObj);
			} else {
				netxObj = (OpenNumber) list.get(j - 1);
			}
			String s = netxObj.getXingsha() + ","
					+ netxObj.getKaijianghezhisplit() + ","
					+ netxObj.getKaijiangjianac() + ","
					+ netxObj.getKaijiangjianlan() + ","
					+ netxObj.getKaijiangliangqijian() + ","
					+ netxObj.getKaijiangweihesplit() + ","
					+ netxObj.getKaijiangxiangjian() + ","
					+ netxObj.getMuiltyhezhisplit();
			Map<String, String> m = new TreeMap<String, String>();
			for (int i = 1; i < 34; i++) {
				if (i < 10)
					m.put("0" + i, "0" + i);
				else
					m.put("" + i, "" + i);
			}
			String[] cs = s.replaceAll(" ", "").split(",");
			for (String a : cs) {
				m.remove(a);
			}
			DaFenQiSSQ ds = new DaFenQiSSQ(openobj);
			ShaNum sn = new ShaNum(netxObj, ds, m.keySet().toString(),
					netxObj.sixRedNum());
			String line = null;
			while (null != (line = br.readLine())) {
				bw.write(line);
			}

			bw.write(shahtml(sn, netxObj));
		}
		bw.write("</table> </body> </html>");
		bw.close();
		br.close();
		// System.out.println("-------------达芬奇密码-------------");
		// System.out.println("第一密码:" + ds.calcOpenNumFirstPWD());
		// System.out.println("第二密码:" + ds.calcOpenNumTwoPWD());
		// System.out.println("第三密码:" + ds.calcOpenNumThreePWD());
		// System.out.println("第四密码:" + ds.calcOpenNumFourPWD());
	}

	private String shahtml(ShaNum sn, OpenNumber on) {
		StringBuilder sb = new StringBuilder();
		sb.append("<tr>");
		sb.append("<th scope=\"col\">杀号方式</th>");
		sb.append("<th scope=\"col\">期号</th>");
		sb.append("<th scope=\"col\">");
		if (null != on)
			sb.append(on.getOpennum());
		sb.append("</th>");
		sb.append("<th scope=\"col\">开奖号</th>");
		sb.append("<th scope=\"col\">");
		if (null != on)
			sb.append(null == on.sixRedNum() ? "*,*,*,*,*,*" : on.sixRedNum())
					.append("|")
					.append(null == on.getN_blue() ? "x" : on.getN_blue());
		sb.append("</th>");
		sb.append("</tr>");
		sb.append("<tr>");
		sb.append("<td class=\"row\">型杀号：</td>");
		sb.append("<td class=\"row\" colspan=\"4\">").append(sn.getXingsha())
				.append("</td>");
		sb.append("</tr>");
		sb.append("<tr>");
		sb.append("<td class=\"row\">开奖号相减：</td>");
		sb.append("<td class=\"row\" colspan=\"4\">").append(sn.getXiangjian())
				.append("</td>");
		sb.append("</tr>");
		sb.append("<tr>");
		sb.append("<td class=\"row\">开奖号减蓝：</td>");
		sb.append("<td class=\"row\" colspan=\"4\">").append(sn.getJianlan())
				.append("</td>");
		sb.append("</tr>");

		sb.append("<tr>");
		sb.append("<td class=\"row\">开奖号减AC值：</td>");
		sb.append("<td class=\"row\" colspan=\"4\">").append(sn.getJianAC())
				.append("</td>");
		sb.append("</tr>");
		sb.append("<tr>");
		sb.append("<td class=\"row\">开奖号和值分拆：</td>");
		sb.append("<td class=\"row\" colspan=\"4\">")
				.append(sn.getHezhisplit()).append("</td>");
		sb.append("</tr>");
		sb.append("<tr>");
		sb.append("<td class=\"row\">开奖号尾值分拆：</td>");
		sb.append("<td class=\"row\" colspan=\"4\">")
				.append(sn.getWeizhisplit()).append("</td>");
		sb.append("</tr>");
		sb.append("<tr>");
		sb.append("<td class=\"row\">开奖号上两期：</td>");
		sb.append("<td class=\"row\" colspan=\"4\">")
				.append(sn.getShangliangqi()).append("</td>");
		sb.append("</tr>");
		sb.append("<tr>");
		sb.append("	<td class=\"row\">开奖号乘减：</td>");
		sb.append("	<td class=\"row\" colspan=\"4\">")
				.append(sn.getChengjian()).append("</td>");
		sb.append("</tr>");
		sb.append("<tr>");
		sb.append("<td class=\"row\">未杀之号：</td>");
		sb.append("<td class=\"row\" colspan=\"4\">").append(sn.getMeisha())
				.append("</td>");
		sb.append("</tr>");
		sb.append("<tr>");
		sb.append("<td class=\"row\" colspan=\"5\">-------------达芬奇密码-------------</td>");

		sb.append("</tr>");
		sb.append("<tr>");
		sb.append("<td class=\"row\">第一密码：</td>");
		sb.append("	<td class=\"row\" colspan=\"4\">").append(sn.getOnepwd())
				.append("</td>");
		sb.append("</tr>");
		sb.append("<tr>");
		sb.append("<td class=\"row\">第二密码：</td>");
		sb.append("<td class=\"row\" colspan=\"4\">").append(sn.getTwopwd())
				.append("</td>");
		sb.append("</tr>");
		sb.append("<tr>");
		sb.append("<td class=\"row\">第三密码：</td>");
		sb.append("<td class=\"row\" colspan=\"4\">").append(sn.getThreepwd())
				.append("</td>");
		sb.append("</tr>");
		sb.append("<tr>");
		sb.append("<td class=\"row\">第四密码：</td>");
		sb.append("<td class=\"row\" colspan=\"4\">").append(sn.getFourpwd())
				.append("</td>");
		sb.append("</tr>");
		return sb.toString();
	}

	private void countAllOpenDatatoHtml(Collection<Cunt> list) throws Exception {
		if (null == list)
			return;
		BufferedWriter bw = null;
		BufferedReader br = null;
		InputStream is = OpenData.class.getResourceAsStream("/NewFile.html");
		File file = new File("count.html");
		bw = new BufferedWriter(new FileWriter(file));
		br = new BufferedReader(new InputStreamReader(is));
		String line = null;
		while (null != (line = br.readLine())) {
			bw.write(line);
		}
		// sb.append("").append()
		// .append("</td>");
		//
		boolean flag = true;
		Cunt ct = null;
		for (Iterator<Cunt> it = list.iterator(); it.hasNext();) {
			ct = it.next();
			if (flag) {
				flag = !flag;
				bw.write("<tr><td class=\"row\">"
						+ (Integer.parseInt(ct.getSeqno()) + 1)
						+ "</td>"
						+ "<td class=\"row\"><input type=\"text\" value=\"\" style=\"width:124px;\"/></td>");

				String tmp = "";
				for (int i = 1; i < 30; i++) {
					tmp += "<td class=\"row\"><input type=\"text\" value=\"\" style=\"width:16px;\"/></td>";
				}
				tmp += "</tr>";
				bw.write(tmp);
				tmp = null;
			}
			bw.write(getStrBycunt(ct));
		}
		bw.write("	</table></body></html>");
		bw.close();
		br.close();
	}

	private String toCoverRed(String s) {
		return s.equals("--") ? s : "<font color=\"red\"><b>" + s
				+ "</b></font>";
	}

	private String getStrBycunt(Cunt ct) {
		StringBuilder sb = new StringBuilder();
		sb.append("<tr><td class=\"row\">").append(ct.getSeqno())
				.append("</td>");
		sb.append("<td class=\"row\">").append(ct.getOpenNo()).append("</td>");
		try {
			Method met = null;
			for (int i = 1; i < 30; i++) {
				met = Cunt.class.getDeclaredMethod("getN_" + i, null);
				sb.append("<td class=\"row\">")
						.append(toCoverRed(met.invoke(ct, null).toString()))
						.append("</td>");
			}
			sb.append("</tr>");
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}

		return sb.toString();
		/**
		 * *
		 * <tr>
		 * <td class="row">badwolf</td>
		 * <td class="row">100</td>
		 * <td class="row">010-110</td>
		 * <td class="row">中国北京</td>
		 * </tr>
		 */
	}
	
	/**
	 * 根据输入的组码的ID来查找共同数码
	 * 
	 * @param params
	 * @return
	 * @throws Exception
	 */
	public String querySelectNo(String params) throws Exception {
		String sql = "SELECT * FROM cardno  ";
		String and = "";

		if (null != params) {
			String tmp = " id in (";
			String[] ps = params.split(",");
			for (String i : ps) {
				tmp += and + i;
				and = ",";
			}
			sql += " where " + tmp + ")";
		}

		java.sql.PreparedStatement prsmt = null;
		java.sql.ResultSet rs = null;
		DB.getInstance();
		prsmt = DB.getInstance().getConn().prepareStatement(sql);
		rs = prsmt.executeQuery();
		List<String> list = new ArrayList<String>();
		while (rs.next()) {
			String str = "";
			String a = "";
			for (int i = 2; i <= 34; i++) {
				String value = rs.getString(i);
				str += a + ("".equals(value) ? "--" : value);
				a = ",";

			}
			list.add(str);
		}
		rs.close();
		prsmt.close();
		return getSelectNO(list);
	}

	private String getSelectNO(List<String> slist) throws Exception {
		if (null == slist || slist.isEmpty())
			throw new Exception("");
		Map<String, String> remap = new HashMap<String, String>();
		for (String s : slist) {
			String[] ses = s.split(",");
			for (int i = 1; i <= 33; i++) {
				if (remap.get("" + i) == null)
					remap.put("" + i, ses[i - 1]);
				else if (remap.get("" + i).equals("--")) {
					continue;
				} else {
					remap.put("" + i, ses[i - 1]);
				}
			}
		}
		Collection<String> keys = remap.values();
		String tmp = "";
		String d = "";
		for (Iterator<String> it = keys.iterator(); it.hasNext();) {
			String v = it.next();
			if (v.equals("--") || v.equals("") || v.equals("  "))
				continue;
			tmp += d + v;
			d = ",";
		}
		String[] sort = tmp.split(",");
		Arrays.sort(sort);
		tmp = "";
		d = "";
		for (String s : sort) {
			tmp += d + s;
			d = ",";
		}
		return tmp;
	}


	public static void main(String[] args) {
		OpenData pd = new OpenData();
//		// String s = null;
//		if (args.length > 0) {
//			try {
//				for (String s : args) {
//					if (s.indexOf(" ") == -1 && s.indexOf(",") == -1)
//						s = s.substring(0, 2) + "," + s.substring(2, 4) + ","
//								+ s.substring(4, 6) + "," + s.substring(6, 8)
//								+ "," + s.substring(8, 10) + ","
//								+ s.substring(10, 12) + ","
//								+ s.substring(12, 14);// +","+s.substring(11);
//
//					String[] ss = s.split(",");
//					int total = Integer.parseInt(ss[0])+Integer.parseInt(ss[1])+Integer.parseInt(ss[2])+Integer.parseInt(ss[3])+Integer.parseInt(ss[4])+Integer.parseInt(ss[5]);
//					pd.insertLastOpenData(new OpenNumber(null, ss[0], ss[1],
//							ss[2], ss[3], ss[4], ss[5], ss[6],total, null,null));
//				}
////				pd.countAllOpenData();
//
////				Process process = Runtime.getRuntime().exec(
////						"cmd.exe /c start count.html");
//			} catch (Exception e) {
//				e.printStackTrace();
//			}
//		}
		 // pd.showPointShahao("2012149");
		 // 下期杀号
		 // pd.showPointShahao("2013008");
		
		 try {
		 pd.showNextShahao();
		 pd.countAllOpenData();
		 Runtime.getRuntime().exec("cmd.exe /c start count.html");
		 pd.contShaHaoToHtml();
		 Thread.sleep(3000);
		 Runtime.getRuntime().exec("cmd.exe /c start ShaCount.html");
		 } catch (Exception e) {
		 e.printStackTrace();
		 }

	}
}
